package com.buddha.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.buddha.api.entity.Brand;
import com.buddha.api.entity.Car;
import com.buddha.api.mapper.BrandMapper;
import com.buddha.api.mapper.CarMapper;
import com.buddha.api.service.ICarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mybatis-plus
 * @since 2023-07-06
 */
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements ICarService {
    @Resource
    CarMapper carMapper;

    @Resource
    BrandMapper brandMapper;

    public Boolean InsertCar(Car car){
        return carMapper.insert(car)>0;
    }

    @Override
    public List<Car> carSelect(String curBrand, String lvl, String energy, Integer minPrice, Integer maxPrice) {
        QueryWrapper<Brand> wrapper = new QueryWrapper<>();
        wrapper.like("brand_name",curBrand);
        Brand brand = brandMapper.selectOne(wrapper);
        int type = -2;
        int drive = -2;
        switch (lvl){
            case "不限":type = -1;break;
            case "轿车":type = 0;break;
            case "SUV":type = 1;break;
            case "MPV":type = 2;break;
            case "跑车":type = 3;break;
            case "微卡":type = 4;break;
            case "轻客":type = 5;break;
            case "其他":type = 6;break;
        };
        switch (energy){
            case "不限":drive = -1;break;
            case "汽油":drive = 0;break;
            case "柴油":drive = 1;break;
            case "油电混合":drive = 2;break;
            case "电动":drive = 3;break;
            case "其他":drive = 4;break;
        };
        QueryWrapper<Car> carQueryWrapper = new QueryWrapper<>();
        if (type != -1){
            carQueryWrapper.eq("car_class",type);
        }
        if (drive != -1){
            carQueryWrapper.eq("drive_mode",drive);
        }
        carQueryWrapper.eq("brand_id",brand.getBrandId());
        int i = (minPrice + maxPrice) / 2;
        if (i != 0){
            carQueryWrapper.le("car_price_l",i);
            carQueryWrapper.ge("car_price_h",i);
        }
        List<Car> list = list(carQueryWrapper);
        return list;
    }

    @Override
    public List<Car> Recommend() {
        List<Integer> ids = list().stream().map(r -> r.getCarId()).collect(Collectors.toList());
        HashSet<Integer> integers = new HashSet<>();
        while (true){
            integers.add(ids.get((int)(Math.random()*ids.size())));
            if (integers.size() == 4){
                break;
            }
        }
        ArrayList<Car> cars = new ArrayList<>();
        for (Integer id : integers) {
            cars.add(getById(id));
        }
        return cars;
    }
}
